<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">















 
 
 
 
 
 
 
  
  


<html>
  <head>
    <script type="text/javascript" language="JavaScript">
    ORIGINAL_PAGE_PATH = "/appengine/docs/java/datastore/queriesandindexes.html";
    </script>
    
    
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Queries and Indexes - Google App Engine - Google Code</title>
<script type="text/javascript"><!--
(function(){function a(){this.t={};this.tick=function(c){this.t[c]=(new Date).getTime()};this.tick("start")}var b=new a;window.jstiming={Timer:a,load:b};if(window.external&&window.external.pageT)window.jstiming.pt=window.external.pageT;})();

var _tocPath_ = '/appengine/docs/_toc.ezt';
var codesite_token = null;
//--></script>
<link href="../../../../css/codesite.pack.04102009.css" type="text/css" rel="stylesheet"></link>
<script src="../../../../js/codesite_head.pack.04102009.js" type="text/javascript"></script>
<script type="text/javascript">CODESITE_CSITimer['load'].tick('bhs');</script>
<link rel="search" type="application/opensearchdescription+xml" title="Google Code" href="http://code.google.com/osd.xml" />

<!--[if IE]><link rel="stylesheet" type="text/css" href="../../../../css/iehacks.css" /><![endif]-->

    <link href="../../../../css/semantic_headers.css" rel="stylesheet" type="text/css" />
    <link href="../../../css/local_extensions.css" rel="stylesheet" type="text/css" />
  </head>

  <body class="gc-documentation">

    
    
    
</a>

<div id="gb">
 <span>
  
    <a id="lang-dropdown" class="dropdown" href="http://code.google.com" onclick="return false;"><img class="globeicon" src="../../../../images/globe2_small.png"/><span>English</span></a>
  
 </span>
</div>

<div class="gbh" style="left: 0pt;"></div>
<div class="gbh" style="right: 0pt;"></div>


<style type="text/css">
  #gc-topnav h1 {
    padding: 0 0 0 6px;
  }
</style>


<div id="gc-container">
<a name="top"></a>
<div id="skipto">
  <a href="#gc-pagecontent">Skip to page content</a>
  <a href="#gc-toc">Skip to main navigation</a>
</div>

<div id="gc-header">
  <div id="logo"><a href="http://code.google.com">
  
  
     <img src="../../../../images/cleardot.gif" height="1px" width="1px" alt="Google Code Home Page" id="gc-logo-img"/>
  
  
  </a></div>
  <div id="search">
    <div id="searchForm" class="searchForm">
      <form id="cse" action="http://www.google.com/cse" accept-charset="utf-8" class="gsc-search-box" onsubmit="executeGSearch(document.getElementById('gsearchInput').value); return false;">
      <noscript>
      <input type="hidden" name="cref" value="http://code.google.com/cse/googlecode-context.xml"/>
      </noscript>
        <table class="gsc-search-box" cellpadding="0" cellspacing="0">
          <tbody>
            <tr>
              <td class="gsc-input">
                <input id="gsearchInput" type="text" name="q" maxlength="2048" class="gsc-input" autocomplete="off" title="Google Code Search" style="width:345px"/>
              </td>
              <td class="gsc-search-button">
                <div id="cs-searchresults" onclick="event.cancelBubble = true;"></div>
                <input title="Search" id="gsearchButton" class="gsc-search-button" name="sa" value="Search" type="submit"/>
              </td>
            </tr>
            <tr>
              <td colspan="2" class="greytext">e.g. "templates" or "datastore"</td>
            </tr>
          </tbody>
        </table>
      </form>
    </div> <!-- end searchForm -->
  </div> <!-- end search -->
</div> <!-- end gc-header -->


<div id="codesiteContent">

<a name="gc-topnav-anchor"></a>
<div id="gc-topnav">
  <h1>Google App Engine</h1>
  <ul id="docs" class="gc-topnav-tabs">

    <li id="home_link">
      <a href="../../../index.html" title="Google App Engine home page">Home</a>
    </li>
  
    <li id="docs_link">
      <a href="../../index.html" class="selected" title="Official Google App Engine documentation">Docs</a>
    </li>
  
    <li id="faq_link">
      <a href="../../../kb/index.html" title="Answers to frequently asked questions about Google App Engine">FAQ</a>
    </li>
  
    <li id="articles_link">
      <a href="../../../articles/index.html" title="Focused articles and tutorials for Google App Engine developers">Articles</a>
    </li>
  
    <li>
      <a href="http://googleappengine.blogspot.com/" title="Official Google App Engine blog">Blog</a>
    </li>
  
    <li>
      <a href="../../../community.html" title="Community home for Google App Engine">Community</a>
    </li>
  
    <li>
      <a href="../../../terms.html" title="Google App Engine terms of service">Terms</a>
    </li>
  
    <li>
      <a href="../../../downloads.html" title="Download Google App Engine">Download</a>
    </li>
  

  </ul>
</div> <!-- end gc-topnav -->

    <div class="g-section g-tpl-170">

      <div class="g-unit g-first" id="gc-toc">
        <ul>
  <li><a href="../../../downloads.html">Downloads</a></li>
  <li><a href="http://code.google.com/status/appengine">System Status</a></li>
  <li><a href="http://code.google.com/p/googleappengine/issues/list">Issue Tracker</a></li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Getting Started</h2>
    <ul>
      <li><a href="../../whatisgoogleappengine.html">What Is Google App Engine?</a></li>
      <li><a href="../gettingstarted/index.html">Java</a>
        <ul>
              <li><a href="../gettingstarted/introduction.html">Introduction</a></li>
    <li><a href="../gettingstarted/installing.html">Installing the Java SDK</a></li>
    <li><a href="../gettingstarted/creating.html">Creating a Project</a></li>
    <li><a href="../gettingstarted/usingusers.html">Using the Users Service</a></li>
    <li><a href="../gettingstarted/usingjsps.html">Using JSPs</a></li>
    <li><a href="../gettingstarted/usingdatastore.html">Using the Datastore with JDO</a></li>
    <li><a href="../gettingstarted/staticfiles.html">Using Static Files</a></li>
    <li><a href="../gettingstarted/uploading.html">Uploading Your Application</a></li>

        </ul>
      </li>
      <li><a href="../../python/gettingstarted/index.html">Python</a>
        <ul>
            <li><a href="../../python/gettingstarted/introduction.html">Introduction</a></li>
  <li><a href="../../python/gettingstarted/devenvironment.html">The Development Environment</a></li>
  <li><a href="../../python/gettingstarted/helloworld.html">Hello, World!</a></li>
  <li><a href="../../python/gettingstarted/usingwebapp.html">Using the webapp Framework</a></li>
  <li><a href="../../python/gettingstarted/usingusers.html">Using the Users Service</a></li>
  <li><a href="../../python/gettingstarted/handlingforms.html">Handling Forms With webapp</a></li>
  <li><a href="../../python/gettingstarted/usingdatastore.html">Using the Datastore</a></li>
  <li><a href="../../python/gettingstarted/templates.html">Using Templates</a></li>
  <li><a href="../../python/gettingstarted/staticfiles.html">Using Static Files</a></li>
  <li><a href="../../python/gettingstarted/uploading.html">Uploading Your Application</a></li>

        </ul>
      </li>
    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Java <sup class="new">Early Look</sup></h2>
    <ul>
          <li><a href="../overview.html">Overview</a></li>
    <li><a href="../runtime.html">Servlet Environment</a></li>
    <li><a href="index.html">Storing Data</a>
      <ul>
            <li><a href="overview.html">Overview</a></li>
    <li><a href="usingjdo.html">Using JDO</a></li>
    <li><a href="dataclasses.html">Defining Data Classes</a></li>
    <li><a href="creatinggettinganddeletingdata.html">Creating, Getting and Deleting Data</a></li>
    <li><a href="queriesandindexes.html">Queries and Indexes</a></li>
    <li><a href="transactions.html">Transactions</a></li>
    <li><a href="relationships.html">Relationships</a></li>
    <li><a href="usingjpa.html">Using JPA</a></li>
    <li><a href="../javadoc/com/google/appengine/api/datastore/package-summary.html">Low-level API</a></li>

      </ul>
    </li>
    <li><a href="../apis.html">Services</a>
      <ul>
        <li><a href="../memcache/index.html">Memcache</a>
          <ul>
                <li><a href="../memcache/overview.html">Overview</a></li>
    <li><a href="../memcache/usingjcache.html">Using JCache</a></li>
    <li><a href="../javadoc/com/google/appengine/api/memcache/package-summary.html">Low-level API</a></li>

          </ul>
        </li>
        <li><a href="../urlfetch/index.html">URL Fetch</a>
          <ul>
                <li><a href="../urlfetch/overview.html">Overview</a></li>
    <li><a href="../urlfetch/usingjavanet.html">Using java.net</a></li>
    <li><a href="../javadoc/com/google/appengine/api/urlfetch/package-summary.html">Low-level API</a></li>

          </ul>
        </li>
        <li><a href="../mail/index.html">Mail</a>
          <ul>
                <li><a href="../mail/overview.html">Overview</a></li>
    <li><a href="../mail/usingjavamail.html">Using JavaMail</a></li>
    <li><a href="../javadoc/com/google/appengine/api/mail/package-summary.html">Low-level API</a></li>

          </ul>
        </li>
        <li><a href="../images/index.html">Images</a>
          <ul>
                <li><a href="../images/overview.html">Overview</a></li>
    <li><a href="../javadoc/com/google/appengine/api/images/package-summary.html">API Reference</a></li>

          </ul>
        </li>
        <li><a href="../users/index.html">Google Accounts</a>
          <ul>
                <li><a href="../users/overview.html">Overview</a></li>
    <li><a href="../javadoc/com/google/appengine/api/users/package-summary.html">API Reference</a></li>

          </ul>
        </li>
      </ul>
    </li>
    <li><a href="../javadoc/index.html">Javadoc Reference</a></li>
    <li><a href="../jrewhitelist.html">JRE Class White List</a></li>
    <li><a href="../config/index.html">Configuration</a>
      <ul>
            <li><a href="../config/webxml.html">Deployment Descriptor</a></li>
    <li><a href="../config/appconfig.html">App Config</a></li>
    <li><a href="../config/indexconfig.html">Index Config</a></li>
    <li><a href="../config/cron.html">Scheduled Tasks</a></li>

      </ul>
    </li>
    <li><a href="../tools/index.html">Tools</a>
      <ul>
            <li><a href="../tools/devserver.html">Development Server</a></li>
    <li><a href="../tools/uploadinganapp.html">Uploading and Managing</a></li>
    <li><a href="../tools/eclipse.html">Google Plugin for Eclipse</a></li>
    <li><a href="../tools/ant.html">Using Apache Ant</a></li>

      </ul>
    </li>
    <li><a href="../howto/index.html">How-To</a>
      <ul>
              <li><a href="../howto/unittesting.html">Unit Testing</a></li>

      </ul>
    </li>

    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Python</h2>
    <ul>
          <li><a href="../../python/overview.html">Overview</a></li>
    <li><a href="../../python/runtime.html">CGI Environment</a></li>
    <li><a href="../../python/datastore/index.html">Storing Data</a>
      <ul>
             <li><a href="../../python/datastore/overview.html">Overview</a></li>
     <li><a href="../../python/datastore/entitiesandmodels.html">Entities and Models</a></li>
     <li><a href="../../python/datastore/creatinggettinganddeletingdata.html">Creating, Getting and Deleting Data</a></li>
     <li><a href="../../python/datastore/keysandentitygroups.html">Keys and Entity Groups</a></li>
     <li><a href="../../python/datastore/queriesandindexes.html">Queries and Indexes</a></li>
     <li><a href="../../python/datastore/transactions.html">Transactions</a></li>
     <li><a href="../../python/datastore/typesandpropertyclasses.html">Types and Property Classes</a></li>
     <li><a href="../../python/datastore/gqlreference.html">GQL Reference</a></li>

     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/datastore/modelclass.html">Model</a></li>
         <li><a href="../../python/datastore/expandoclass.html">Expando</a></li>
         <li><a href="../../python/datastore/polymodelclass.html">PolyModel</a></li>
         <li><a href="../../python/datastore/propertyclass.html">Property</a></li>
         <li><a href="../../python/datastore/queryclass.html">Query</a></li>
         <li><a href="../../python/datastore/gqlqueryclass.html">GqlQuery</a></li>
         <li><a href="../../python/datastore/keyclass.html">Key</a></li>
         <li><a href="../../python/datastore/functions.html">Functions</a></li>
         <li><a href="../../python/datastore/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

      </ul>
    </li>
    <li><a href="../../python/apis.html">Services</a>
      <ul>
        <li><a href="../../python/memcache/index.html">Memcache</a>
          <ul>
                 <li><a href="../../python/memcache/overview.html">Overview</a></li>
      <li><a href="../../python/memcache/usingmemcache.html">Using Memcache</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/memcache/clientclass.html">Client</a></li>
         <li><a href="../../python/memcache/functions.html">Functions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../../python/urlfetch/index.html">URL Fetch</a>
          <ul>
                 <li><a href="../../python/urlfetch/overview.html">Overview</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/urlfetch/fetchfunction.html">The fetch Function</a></li>
         <li><a href="../../python/urlfetch/responseobjects.html">Response Objects</a></li>
         <li><a href="../../python/urlfetch/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../../python/mail/index.html">Mail</a>
          <ul>
                 <li><a href="../../python/mail/overview.html">Overview</a></li>
     <li><a href="../../python/mail/sendingmail.html">Sending Mail</a></li>
     <li><a href="../../python/mail/attachments.html">Attachments</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/mail/emailmessageclass.html">EmailMessage</a></li>
         <li><a href="../../python/mail/emailmessagefields.html">Message Fields</a></li>
         <li><a href="../../python/mail/functions.html">Functions</a></li>
         <li><a href="../../python/mail/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../../python/images/index.html">Images</a>
          <ul>
                 <li><a href="../../python/images/overview.html">Overview</a></li>
     <li><a href="../../python/images/installingPIL.html">Installing PIL</a></li>
     <li><a href="../../python/images/usingimages.html">Using the Images API</a></li>
     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/images/imageclass.html">Image</a></li>
         <li><a href="../../python/images/functions.html">Functions</a></li>
         <li><a href="../../python/images/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
        <li><a href="../../python/users/index.html">Google Accounts</a>
          <ul>
                 <li><a href="../../python/users/overview.html">Overview</a></li>
     <li><a href="../../python/users/userobjects.html">User Objects</a></li>
     <li><a href="../../python/users/loginurls.html">Login URLs</a></li>
     <li><a href="../../python/users/adminusers.html">Admin Users</a></li>

     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/users/userclass.html">User</a></li>
         <li><a href="../../python/users/functions.html">Functions</a></li>
         <li><a href="../../python/users/exceptions.html">Exceptions</a></li>
       </ul>
     </li>

          </ul>
        </li>
      </ul>
    </li>
    <li><a href="../../python/config/index.html">Configuration</a>
      <ul>
            <li><a href="../../python/config/appconfig.html">App Config</a></li>
    <li><a href="../../python/config/indexconfig.html">Index Config</a></li>
    <li><a href="../../python/config/cron.html">Scheduled Tasks</a></li>

      </ul>
    </li>
    <li><a href="../../python/tools/index.html">Tools</a>
      <ul>
            <li><a href="../../python/tools/devserver.html">Development Server</a></li>
    <li><a href="../../python/tools/uploadinganapp.html">Uploading and Managing</a></li>
    <li><a href="../../python/tools/uploadingdata.html">Uploading Data</a></li>
    <li><a href="../../python/tools/webapp/index.html">webapp Framework</a>
      <ul>
             <li><a href="../../python/tools/webapp/overview.html">Overview</a></li>
     <li><a href="../../python/tools/webapp/running.html">Running the Application</a></li>
     <li><a href="../../python/tools/webapp/requesthandlers.html">Request Handlers</a></li>
     <li><a href="../../python/tools/webapp/requestdata.html">Request Data</a></li>
     <li><a href="../../python/tools/webapp/buildingtheresponse.html">Building the Response</a></li>
     <li><a href="../../python/tools/webapp/redirects.html">Redirects, Headers and Status Codes</a></li>
     

     <li><span class="tlw-title tlw-expanded">Reference</span>
       <ul>
         <li><a href="../../python/tools/webapp/requestclass.html">Request</a></li>
         <li><a href="../../python/tools/webapp/responseclass.html">Response</a></li>
         <li><a href="../../python/tools/webapp/requesthandlerclass.html">RequestHandler</a></li>
         <li><a href="../../python/tools/webapp/wsgiapplicationclass.html">WSGIApplication</a></li>
         <li><a href="../../python/tools/webapp/utilmodule.html">Utility Functions</a></li>
         
       </ul>
     </li>

      </ul>
    </li>
    <li><a href="../../python/tools/libraries.html">Third-party Libraries</a></li>

      </ul>
    </li>
    <li><a href="../../python/howto/index.html">How-To</a>
      <ul>
              <li><a href="../../python/howto/usinggdataservices.html">Google Data Services</a></li>

      </ul>
    </li>

    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Managing Your App</h2>
    <ul>
      <li><a href="../../theadminconsole.html">The Admin Console</a></li>
      <li><a href="../../quotas.html">Quotas</a></li>
      <li><a href="../../billing.html">Billing</a></li>
    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><h2>Resources</h2>
    <ul>
      <li><a href="../../../kb/index.html">FAQ</a></li>
      <li><a href="../../../articles/index.html">Articles</a></li>
      <li><a href="http://appengine-cookbook.appspot.com/">Cookbook</a></li>
      <li><a href="http://appgallery.appspot.com/">App Gallery</a></li>
      <li><a href="http://code.google.com/p/googleappengine/">SDK Code</a></li>
      <li><a href="http://code.google.com/p/google-app-engine-samples/">Sample Apps Code</a></li>
      <li><a href="../../../community.html">Discussion Groups</a></li>
    </ul>
  </li>
</ul>
<div class="line"></div>
<ul>
  <li><a href="../../roadmap.html">Product Roadmap</a></li>
  <li><a href="http://code.google.com/p/googleappengine/wiki/SdkReleaseNotes">Release Notes</a></li>
  <li><a href="../../revision_history.html">Revision History</a></li>
</ul>

        <a class="hidden" href="#gc-topnav-anchor">More Google App Engine resource links</a>
      </div>

      <div class="g-unit" id="gc-pagecontent">
        <h1 class="page_title">Queries and Indexes</h1>


















<p>Every datastore query uses an index, a table that contains the results for the query in the desired order.  An App Engine application defines its indexes in a configuration file named <code>datastore-indexes.xml</code>.  The development web server can automatically generate suggestions for this file as it encounters queries that do not yet have indexes configured.</p>

<p>The index-based query mechanism supports most common kinds of queries, but it does not support some queries you may be used to from other database technologies.  Restrictions on queries, and their explanations, are described below.</p>

<ul>
  <li><a href="#Introducing_Queries">Introducing Queries</a></li>
  <li><a href="#Introducing_Indexes">Introducing Indexes</a></li>
  <li><a href="#Defining_Indexes_With_Configuration">Defining Indexes With Configuration</a></li>
  <li><a href="#Queries_on_Keys">Queries on Keys</a></li>
  <li><a href="#Restrictions_on_Queries">Restrictions on Queries</a></li>
  <li><a href="#Big_Entities_and_Exploding_Indexes">Big Entities and Exploding Indexes</a></li>
</ul>


<h2 id="Introducing_Queries">Introducing Queries</h2>

<p>A query retrieves entities from the datastore that meet a set of conditions.  The query specifies an entity kind, zero or more conditions based on entity property values (sometimes called "filters"), and zero or more sort order descriptions.  When the query is executed, it fetches all entities of the given kind that meet all of the given conditions, sorted in the order described.</p>

<p>A query can also return <a href="#Queries_on_Keys">just the keys</a> of the result entities instead of the entities themselves.</p>


<p>JDO can perform queries for entities that meet certain criteria.  You can also use a JDO Extent to represent the collection of every entity of a kind (every stored object of a class).</p>

<h3>Queries with JDOQL</h3>

<p>JDO includes a query language for retrieving objects that meet a set of criteria.  This language, called JDOQL, refers to JDO data classes and fields directly, and includes type checking for query parameters and results.  JDOQL is similar to SQL, but is more appropriate for object-oriented databases like the App Engine datastore.  (The App Engine datastore does not support SQL queries with the JDO interface.)</p>

<p>The query API supports several calling styles.  You can specify a complete query in a string, using the JDOQL string syntax.  You can also specify some or all parts of the query by calling methods on the query object.</p>

<p>Here is a simple example of a query using the method style of calling, with one filter and one sort order, using parameter substitution for the value used in the filter.  The Query object's <code>execute()</code> method is called with the values to substitute in the query, in the order they are declared.</p>

<pre class="prettyprint">
import java.util.List;
import javax.jdo.Query;

// ...

    Query query = pm.newQuery(Employee.class);
    query.setFilter("lastName == lastNameParam");
    query.setOrdering("hireDate desc");
    query.declareParameters("String lastNameParam");

    try {
        List&lt;Employee&gt; results = (List&lt;Employee&gt;) query.execute("Smith");
        if (results.iterator().hasNext()) {
            for (Employee e : results) {
                // ...
            }
        } else {
            // ... no results ...
        }
    } finally {
        query.closeAll();
    }
</pre>

<p>Here is the same query using the string syntax:</p>

<pre class="prettyprint">
    Query query = pm.newQuery("select from Employee " +
                              "where lastName == lastNameParam " +
                              "order by hireDate desc " +
                              "parameters String lastNameParam")

    List&lt;Employee&gt; results = (List&lt;Employee&gt;) query.execute("Smith");
</pre>

<p>You can mix these styles of defining the query.  For example:</p>

<pre class="prettyprint">
    Query query = pm.newQuery(Employee.class,
                              "lastName == lastNameParam order by hireDate desc");
    query.declareParameters("String lastNameParam");

    List&lt;Employee&gt; results = (List&lt;Employee&gt;) query.execute("Smith");
</pre>

<p>You can reuse a single Query instance with different values substituted for the parameters by calling the <code>execute()</code> method multiple times.  Each call performs the query and returns the results as a collection.</p>

<p>The JDOQL string syntax supports value literals within the string for string values and numeric values.  Surround strings in either single-quotes (<code>'</code>) or double-quotes (<code>&quot;</code>).  All other value types must use parameter substitution.  Here is an example using a string literal value:</p>

<pre class="prettyprint">
    Query query = pm.newQuery(Employee.class,
                              "lastName == 'Smith' order by hireDate desc");
</pre>


<h3>Query Filters</h3>

<p>A <b>filter</b> specifies a field name, an operator, and a value.  The value must be provided by the app; it cannot refer to another property, or be calculated in terms of other properties.  The operator can be any of the following: <code>&lt; &lt;= == &gt;= &gt;</code></p>

<p class="note"><b>Note:</b> The Java datastore interface does not support the <code>!=</code> and <code>IN</code> filter operators that are implemented in the Python datastore interface.  (In the Python interface, these operators are implemented in the client-side libraries as multiple datastore queries; they are not features of the datastore itself.)</p>

<p>The subject of a filter can be any object field, including the primary key and the entity group parent (see <a href="transactions.html">Transactions</a>).</p>

<p>An entity must match all filters to be a result.  In the JDOQL string syntax, multiple filters are specified separated by <code>&amp;&amp;</code> (logical "and").  Other logical combinations of filters (logical "or", "not") are not supported.</p>

<p>Due to the way the App Engine datastore executes queries, a single query cannot use inequality filters (<code>&lt; &lt;= &gt;= &gt;</code>) on more than one property.  Multiple inequality filters on the same property (such as querying for a range of values) are permitted.  See <a href="#Restrictions_on_Queries">Restrictions on Queries</a>.</p>

<pre class="prettyprint">
    query.setFilter("lastName == 'Smith' &amp;&amp; hireDate &gt; hireDateMinimum");
    query.declareParameters("Date hireDateMinimum");
</pre>


<h3>Query Sort Orders</h3>

<p>A <b>sort order</b> specifies a property and a direction, either ascending or descending.  The results are returned sorted by the given orders, in the order they were specified.  If no sort orders are specified for the query, the results are ordered by their entity keys.</p>

<p>Due to the way the App Engine datastore executes queries, if a query specifies inequality filters on a property and sort orders on other properties, the property used with the inequality filters must be ordered <i>before</i> the other properties.  See <a href="#Restrictions_on_Queries">Restrictions on Queries</a>.</p>

<pre class="prettyprint">
    query.setOrdering("hireDate desc, firstName asc");
</pre>


<h3>Query Ranges</h3>

<p>A query can specify a <b>range</b> of results to be returned to the application.  The range specifies which result in the complete result set should be the first one returned, and which should be the last, using numeric indexes, starting with 0 for the first result.  For example, a range of <code>5, 10</code> returns the 6th, 7th, 8th, 9th and 10th results.</p>

<p>The starting offset has implications for performance: the datastore must retrieve and then discard all results prior to the starting offset.  For example, a query with a range of <code>5, 10</code> fetches 10 results from the datastore, then discards the first 5 and returns the remaining 5 to the application.</p>

<pre class="prettyprint">
    query.setRange(5, 10);
</pre>


<h3>Extents</h3>

<p>A JDO Extent represents every object in the datastore of a particular class..</p>

<p>You start an Extent using the PersistenceManager's <code>getExtent()</code> method, passing it the data class.  The Extent class implements the Iterable interface for accessing results.  When you are done accessing results, you call the <code>closeAll()</code> method.</p>

<p>The following example iterates over every Employee object in the datastore:</p>

<pre class="prettyprint">
import java.util.Iterator;
import javax.jdo.Extent;

// ...

    Extent extent = pm.getExtent(Employee.class, false);
    for (Employee e : extent) {
        // ...
    }
    extent.closeAll();
</pre>

<p>An extent retrieves results in batches, and can exceed the 1,000-result limit that applies to queries.</p>




<h2 id="Introducing_Indexes">Introducing Indexes</h2>

<p>The App Engine datastore maintains an index for every query an application intends to make.  As the application makes changes to datastore entities, the datastore updates the indexes with the correct results.  When the application executes a query, the datastore fetches the results directly from the corresponding index.</p>

<p>An application has an index for each combination of kind, filter property and operator, and sort order used in a query.  Consider the example query, stated in JDOQL:</p>



<pre>
select from Person where lastName == "Smith"
                      &amp;&amp; height &lt; 72
                order by height desc
</pre>


<p>The index for this query is a table of keys for entities of the kind <code>Person</code>, with columns for the values of the <code>height</code> and <code>lastName</code> properties.  The index is sorted by <code>height</code> in descending order.</p>

<p>Two queries of the same form but with different filter values use the same index.  For example, the following query uses the same index as the query above:</p>



<pre>
select from Person where lastName == "Jones"
                      &amp;&amp; height &lt; 64
                order by height desc
</pre>


<p>The datastore executes a query using the following steps:</p>

<ol>
  <li>The datastore identifies the index that corresponds with the query's kind, filter properties, filter operators, and sort orders.</li>
  <li>The datastore starts scanning the index at the first entity that meets all of the filter conditions using the query's filter values.</li>
  <li>The datastore continues to scan the index, returning each entity, until it finds the next entity that does not meet the filter conditions, until it reaches the end of the index, or until it has collected the maximum number of results requested by the query.</li>
</ol>

<p>An index table contains columns for every property used in a filter or sort order.  The rows are sorted by the following aspects, in order:</p>

<ul>
  <li>ancestors</li>
  <li>property values used in equality filters</li>
  <li>property values used in inequality filters</li>
  <li>property values used in sort orders</li>
</ul>



<p>This puts all results for every possible query that uses this index in consecutive rows in the table.</p>




<p>This mechanism supports a wide range of queries and is suitable for most applications.  However, it does not support some kinds of queries you may be used to from other database technologies.</p>


<h3>Entities Without a Filtered Property Are Never Returned by a Query</h3>

<p>An index only contains entities that have every property referred to by the index.  If an entity does not have a property referred to by an index, the entity will not appear in the index, and will never be a result for the query that uses the index.</p>

<p>Note that the App Engine datastore makes a distinction between an entity that does not possess a property and an entity that possesses the property with a null value (<code>null</code>).  If you want every entity of a kind to be a potential result for a query, you can use a JDO or JPA data class, which always assigns a value to every property that corresponds to a field in the class.</p>


<h3>Properties that Aren't Indexed</h3>

<p>Property values that aren't indexed are not findable by queries. This includes properties that are marked as not indexed, as well as properties with values of the long text value type (Text) or the long binary value type (Blob).</p>

<p>A query with a filter or sort order on a property will never match an entity whose value for the property is a Text or Blob, or which was written with that property marked as not indexed.  Properties with such values behave as if the property is not set with regard to query filters and sort orders.</p>


<h3>Property Values of Mixed Types are Ordered By Type</h3>

<p>When two entities have properties of the same name but of different value types, an index of the property sorts the entities first by value type, then by an order appropriate to the type.  For example, if two entities each have a property named "age," one with an integer value and one with a string value, the entity with the integer value will always appear before the entity with the string value when sorted by the "Age" property, regardless of the values themselves.</p>

<p>This is especially worth noting in the case of integers and floating point numbers, which are treated as separate types by the datastore.  A property with the integer value <code>38</code> is sorted before a property with the floating point value <code>37.5</code>, because all integers are sorted before floats.</p>


<p>(If you're using JDO or JPA, this situation does not arise unless you modify a field's type without updating existing entities in the datastore, or use the low-level datastore API or a non-Java API.)</p>



<h2 id="Defining_Indexes_With_Configuration">Defining Indexes With Configuration</h2>

<p>App Engine builds indexes for several simple queries by default.  For other queries, the application must specify the indexes it needs in a configuration file named <code>datastore-indexes.xml</code>.  If the application running under App Engine tries to perform a query for which there is no corresponding index (either provided by default or described in <code>datastore-indexes.xml</code>), the query will fail.</p>

<p>App Engine provides automatic indexes for the following forms of queries:</p>
<ul>
  <li>queries using only equality and ancestor filters</li>
  <li>queries using only inequality filters (which can only be of a single property)</li>
  <li>queries with only one sort order on a property, either ascending or descending</li>
</ul>

<p>Other forms of queries require their indexes to be specified in <code>datastore-indexes.xml</code>, including:</p>
<ul>
  <li>queries with multiple sort orders</li>
  <li>queries with a sort order on keys in descending order</li>
  <li>queries with one or more inequality filters on a property and one or more equality filters over other properties</li>
  <li>queries with inequality filters and ancestor filters</li>
</ul>

<p>The development web server makes managing index configuration easy: Instead of failing to execute a query that does not have an index and requires it, the development web server can generate configuration for an index that would allow the query to succeed.  If your local testing of your application calls every possible query the application will make (every combination of kind, ancestor, filter and sort order), the generated entries will represent a complete set of indexes.  If your testing might not exercise every possible query form, you can review and adjust the index configuration before uploading the application.</p>


<p>You can define indexes manually using a configuration file named <code>datastore-indexes.xml</code> in the <code>WEB-INF/</code> directory of your application's WAR.  If you have automatic index configuration enabled (see below), the development server creates an index configuration in a file named <code>datastore-indexes-auto.xml</code> in a directory named <code>WEB-INF/appengine-generated/</code>, and uses both files to determine the full set of indexes.</p>

<p>Consider once again the following example query:</p>

<pre>
select from Person where lastName = 'Smith'
                      &amp;&amp; height < 72
                   order by height desc
</pre>

<p>The configuration for the index needed by this query would appear in <code>datastore-indexes.xml</code> as follows:</p>

<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;datastore-indexes
  xmlns="http://appengine.google.com/ns/datastore-indexes/1.0"
  autoGenerate="true"&gt;
    &lt;datastore-index kind="Person" ancestor="false"&gt;
        &lt;property name="lastName" direction="asc" /&gt;
        &lt;property name="height" direction="desc" /&gt;
    &lt;/datastore-index&gt;
&lt;/datastore-indexes&gt;
</pre>

<p>If the <code>&lt;datastore-indexes&gt;</code> element in <code>datastore-indexes.xml</code> has the attribute <code>autoGenerate="true"</code> (as above) or if the app does not have a <code>datastore-indexes.xml</code> file, automatic index configuration is enabled.  With automatic index configuration enabled, if the app performs this query in the development server and no configuration for the index exists, the server adds this index configuration to the <code>datastore-indexes-auto.xml</code> file.</p>

<p>For more information on <code>datastore-indexes.xml</code> and <code>datastore-indexes-auto.xml</code>, see <a href="../config/indexconfig.html">Java Datastore Index Configuration</a>.</p>



<h2 id="Queries_on_Keys">Queries on Keys</h2>


<p>Entity keys can be the subject of a query filter or sort order.  In JDO, you refer to the entity key in the query using the primary key field of the object.  The datastore considers the complete key value for such queries, including the entity's parent path, the kind, and the app-assigned key name string or system-assigned numeric ID.</p>

<p>Because an entity key is unique across all entities in the system, key queries make it easy to retrieve entities of a given kind in batches, such as for a batch dump of the contents of the datastore.  Unlike JDOQL ranges, this works efficiently for any number of entities.</p>




<p>Keys are ordered first by parent path, then by kind, then by key name or ID.  Kinds and key names are strings and are ordered by byte value.  IDs are integers and are ordered numerically.  If entities of the same parent and kind use a mix of key name strings and numeric IDs, entities with numeric IDs are considered to be less than entities with key name strings.  Elements of the parent path are compared similarly: by kind (string), then by key name (string) or ID (number).</p>

<p>Queries involving keys use indexes just like queries involving properties, with one minor difference: Unlike with a property, a query with an equality filter on the key that also has additional filters must use a custom index defined in the app's index configuration file.  As with all queries, the development web server creates appropriate configuration entries in this file when a query that needs a custom index is tested.</p>


<h2 id="Restrictions_on_Queries">Restrictions on Queries</h2>

<p>The nature of the index query mechanism imposes a few restrictions on what a query can do.</p>

<h3 id="Filtering_Or_Sorting_On_a_Property_Requires_That_the_Property_Exists">
 Filtering Or Sorting On a Property Requires That the Property Exists</h3>

<p>A query filter condition or sort order for a property also implies a condition that the entity have a value for the property.</p>

<p>A datastore entity is not required to have a value for a property that other entities of the same kind have.  A filter on a property can only match an entity with a value for the property.  Entities without a value for a property used in a filter or sort order are omitted from the index built for the query.</p>


<h3 id="No_Filter_That_Matches_Entities_That_Do_Not_Have_a_Property">
 No Filter That Matches Entities That Do Not Have a Property</h3>

<p>It is not possible to perform a query for entities that are missing a given property.  One alternative is to create a fixed (modeled) property with a default value of <code>null</code>, then create a filter for entities with <code>null</code> as the property value.</p>


<h3 id="Inequality_Filters_Are_Allowed_On_One_Property_Only">
 Inequality Filters Are Allowed On One Property Only</h3>

<p>A query may only use inequality filters (<code>&lt;</code>, <code>&lt;=</code>, <code>&gt;=</code>, <code>&gt;</code>) on one property across all of its filters.</p>

<p>For example, this query is allowed:</p>



<pre>
select from Person where birthYear &gt;= minBirthYearParam
                      &amp;&amp; birthYear &lt;= maxBirthYearParam
</pre>


<p>However, this query is <i>not</i> allowed, because it uses inequality filters on two different properties in the same query:</p>



<pre>
select from Person where birthYear &gt;= minBirthYearParam
                      &amp;&amp; height &gt;= minHeightParam   // ERROR
</pre>


<p>Filters can combine equal (<code>==</code>) comparisons for different properties in the same query, including queries with one or more inequality conditions on a property.  This is allowed:</p>



<pre>
select from Person where lastName == lastNameParam
                      &amp;&amp; city == cityParam
                      &amp;&amp; birthYear &gt;= minBirthYearParam
</pre>


<p>The query mechanism relies on all results for a query to be adjacent to one another in the index table, to avoid having to scan the entire table for results.  A single index table cannot represent multiple inequality filters on multiple properties while maintaining that all results are consecutive in the table.</p>


<h3 id="Properties_In_Inequality_Filters_Must_Be_Sorted_Before_Other_Sort_Orders">
 Properties In Inequality Filters Must Be Sorted Before Other Sort Orders</h3>

<p>If a query has both a filter with an inequality comparison and one or more sort orders, the query must include a sort order for the property used in the inequality, and the sort order must appear <i>before</i> sort orders on other properties.</p>

<p>This query is <i>not</i> valid, because it uses an inequality filter and does not order by the filtered property:</p>


<pre>
select from Person where birthYear &gt;= minBirthYearParam
                order by lastName                    // ERROR
</pre>


<p>Similarly, this query is not valid because it does not order by the filtered property before ordering by other properties:</p>


<pre>
select from Person where birthYear &gt; minBirthYearParam
                order by lastName, birthYear         // ERROR
</pre>


<p>This query is valid:</p>


<pre>
select from Person where birthYear &gt;= minBirthYearParam
                order by birthYear, lastName
</pre>


<p>To get all results that match an inequality filter, a query scans the index table for the first matching row, then returns all consecutive results until it finds a row that doesn't match.  For the consecutive rows to represent the complete result set, the rows must be ordered by the inequality filter before other sort orders.</p>


<h3 id="Sort_Orders_and_Properties_With_Multiple_Values">Sort Orders and Properties With Multiple Values</h3>

<p>Due to the way properties with multiple values are indexed, the sort order for these properties is unusual:</p>

<ul class="doublespace">
  <li>If the entities are sorted by a multi-valued property in ascending order, the value used for ordering is the smallest value.</li>
  <li>If the entities are sorted by a multi-valued property in descending order, the value used for ordering is the greatest value.</li>
  <li>Other values do not affect the sort order, nor does the number of values.</li>
  <li>In the case of a tie, the key of the entity is used as the tie-breaker.</li>
</ul>

<p>This sort order has the unusual consequence that <code>[1, 9]</code> comes before <code>[4, 5, 6, 7]</code> in both ascending <i>and</i> descending order.</p>

<p>One important caveat is queries with both an equality filter and a sort
order on a multi-valued property. In those queries, the sort order is disregarded.
For single-valued properties, this is a simple optimization. Every result would
have the same value for the property, so the results do not need to be sorted
further.</p>

<p>However, multi-valued properties may have additional values. Since the sort order
is disregarded, the query results may be returned in a different order than if
the sort order were applied. (Restoring the dropped sort order would be
expensive and require extra indices, and this use case is rare, so the query
planner leaves it off.)</p>


<h2 id="Big_Entities_and_Exploding_Indexes">Big Entities and Exploding Indexes</h2>

<p>As described above, every property (that doesn't have a Text or Blob value) of every entity is added to at least one index table, including a simple index provided by default, and any indexes described in the application's <code>datastore-indexes.xml</code> file that refer to the property.  For an entity that has one value for each property, App Engine stores a property value once in its simple index, and once for each time the property is referred to in a custom index.  Each of these index entries must be updated every time the value of the property changes, so the more indexes that refer to the property, the more time it will take to update the property.</p>

<p>To prevent the update of an entity from taking too long, the datastore limits the number of index entries that a single entity can have.  The limit is large, and most applications will not notice.  However, there are some circumstances where you might encounter the limit.  For example, an entity with very many single-value properties can exceed the index entry limit.</p>

<p>Properties with multiple values store each value as a separate entry in an index.  An entity with a single property with very many values can exceed the index entry limit.</p>

<p>Custom indexes that refer to multiple properties with multiple values can get very large with only a few values.  To completely record such properties, the index table must include a row for <i>every permutation of the values</i> of every property for the index.</p>



<p>For example, the following index (described in <code>datastore-indexes.xml</code> syntax) includes the <code>x</code> and <code>y</code> properties for entities of the kind <code>MyModel</code>:</p>

<pre class="prettyprint">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;datastore-indexes&gt;
    &lt;datastore-index kind="MyModel"&gt;
        &lt;property name="x" direction="asc" /&gt;
        &lt;property name="y" direction="asc" /&gt;
    &lt;/datastore-index&gt;
&lt;/datastore-indexes&gt;
</pre>

<p>The following code creates an entity with 2 values for the property <code>x</code> and 2 values for the property <code>y</code>:</p>

<pre class="prettyprint">
        MyModel m = new MyModel();

        m.setX(Arrays.asList("one", "two"));
        m.setY(Arrays.asList("three", "four"));

        pm.makePersistent(m);
</pre>



<p>To accurately represent these values, the index must store 12 property values: 2 each for the built-in indexes on <code>x</code> and <code>y</code>, and 2 for each of the 4 permutations of <code>x</code> and <code>y</code> in the custom index.  With many values of multi-valued properties, this can mean an index must store very many index entries for a single entity.  You could call an index that refers to multiple properties with multiple values an "exploding index," because it can get very large with just a few values.</p>

<p>If a <code>put()</code> would result in a number of index entries that exceeds the limit, the call will fail with an exception.  If you create a new index that would contain a number of index entries that exceeds the limit for any entity when built, queries against the index will fail, and the index will appear in the "Error" state in the Admin Console.</p>



<p>You can avoid exploding indexes by avoiding queries that would require a custom index using a list property.  As described above, this includes queries with multiple sort orders, a mix of equality and inequality filters, and ancestor filters.</p>



      </div><!-- end gc-pagecontent -->
   </div><!-- end gooey wrapper -->

    </div> <!-- end codesite content -->

<div id="gc-footer" dir="ltr">
  <div class="text">
    
      <div class="notice"><div id="notice" style="text-align: center; border: 1em 0em 1em 0em">
  Except as otherwise <a
  href="http://code.google.com/policies.html#restrictions">noted</a>,
  the content of this page is licensed under the <a rel="license"
  href="http://creativecommons.org/licenses/by/2.5/">Creative Commons
  Attribution 2.5 License</a>, and code samples are licensed under the
  <a rel="license" href="http://www.apache.org/licenses/LICENSE-2.0">Apache
  2.0 License</a>.
<!-- <rdf:RDF xmlns="http://web.resource.org/cc/" 
              xmlns:dc="http://purl.org/dc/elements/1.1/"
              xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <Work rdf:about="">
    <license rdf:resource="http://creativecommons.org/licenses/by/2.5/" />
  </Work>
  <License rdf:about="http://creativecommons.org/licenses/by/2.5/">
    <permits rdf:resource="http://web.resource.org/cc/Reproduction"/>
    <permits rdf:resource="http://web.resource.org/cc/Distribution"/>
    <requires rdf:resource="http://web.resource.org/cc/Notice"/>
    <requires rdf:resource="http://web.resource.org/cc/Attribution"/>
    <permits rdf:resource="http://web.resource.org/cc/DerivativeWorks"/>
  </License>
</rdf:RDF> -->
</div>
Java is a registered trademark of Sun Microsystems, Inc.</div>
    
    &copy;2009 Google -
    <a href="http://code.google.com">Code Home</a> -
    <a href="http://www.google.com/accounts/TOS">Terms of Service</a> -
    <a href="http://www.google.com/privacy.html">Privacy Policy</a> -
    <a href="http://code.google.com/more">Site Directory</a>
    <br /> <br />
    Google Code offered in:
    <a href="http://code.google.com/intl/en">English</a> -
    <a href="http://code.google.com/intl/es">Español</a> -
    <a href="http://code.google.com/intl/ja">日本語</a> -
    <a href="http://code.google.com/intl/ko">한국어</a> -
    <a href="http://code.google.com/intl/pt-BR">Português</a> -
    <a href="http://code.google.com/intl/ru">Pусский</a> -
    <a href="http://code.google.com/intl/zh-CN">中文(简体)</a> -
    <a href="http://code.google.com/intl/zh-TW">中文(繁體)</a>
  </div>
</div><!-- end gc-footer -->

</div><!-- end gc-containter -->

<script type="text/javascript">CODESITE_CSITimer['load'].tick('ats');</script>
<script src="../../../../js/codesite_tail.pack.04102009.js" type="text/javascript"></script>






  </body>
</html>


